package com.governtalk.backend.controller;

import com.governtalk.backend.dto.wrongquestion.WrongQuestionDto;
import com.governtalk.backend.service.WrongQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/wrong-questions")
@CrossOrigin(origins = "*")
public class WrongQuestionController {
    
    @Autowired
    private WrongQuestionService wrongQuestionService;
    
    /**
     * 添加错题到错题本
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> addWrongQuestion(@RequestBody WrongQuestionDto wrongQuestionDto) {
        try {
            WrongQuestionDto result = wrongQuestionService.addWrongQuestion(wrongQuestionDto);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "错题已添加到错题本");
            response.put("data", result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "添加错题失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 批量添加错题到错题本
     */
    @PostMapping("/batch")
    public ResponseEntity<Map<String, Object>> addWrongQuestions(@RequestBody List<WrongQuestionDto> wrongQuestionDtos) {
        try {
            List<WrongQuestionDto> results = wrongQuestionService.addWrongQuestions(wrongQuestionDtos);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "批量添加错题成功");
            response.put("data", results);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "批量添加错题失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取用户错题列表
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getWrongQuestions(
            @RequestParam Long userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "errorTime") String sortBy,
            @RequestParam(defaultValue = "desc") String sortOrder) {
        try {
            Sort sort = sortOrder.equals("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<WrongQuestionDto> wrongQuestions = wrongQuestionService.getWrongQuestionsByUserId(userId, pageable);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", wrongQuestions);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取错题列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 搜索错题
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchWrongQuestions(
            @RequestParam Long userId,
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by("errorTime").descending());
            Page<WrongQuestionDto> wrongQuestions = wrongQuestionService.searchWrongQuestions(userId, keyword, pageable);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", wrongQuestions);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "搜索错题失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 根据题型获取错题
     */
    @GetMapping("/by-type")
    public ResponseEntity<Map<String, Object>> getWrongQuestionsByType(
            @RequestParam Long userId,
            @RequestParam String type,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by("errorTime").descending());
            Page<WrongQuestionDto> wrongQuestions = wrongQuestionService.getWrongQuestionsByType(userId, type, pageable);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", wrongQuestions);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取错题失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 根据复习状态获取错题
     */
    @GetMapping("/by-review-status")
    public ResponseEntity<Map<String, Object>> getWrongQuestionsByReviewStatus(
            @RequestParam Long userId,
            @RequestParam Boolean isReviewed,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by("errorTime").descending());
            Page<WrongQuestionDto> wrongQuestions = wrongQuestionService.getWrongQuestionsByReviewStatus(userId, isReviewed, pageable);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", wrongQuestions);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取错题失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 更新复习状态
     */
    @PutMapping("/{id}/review-status")
    public ResponseEntity<Map<String, Object>> updateReviewStatus(
            @PathVariable Long id,
            @RequestParam Boolean isReviewed,
            @RequestParam(required = false) Integer masteryLevel) {
        try {
            WrongQuestionDto result = wrongQuestionService.updateReviewStatus(id, isReviewed, masteryLevel);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "复习状态已更新");
            response.put("data", result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新复习状态失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 更新错误原因
     */
    @PutMapping("/{id}/error-reason")
    public ResponseEntity<Map<String, Object>> updateErrorReason(
            @PathVariable Long id,
            @RequestParam String errorReason) {
        try {
            WrongQuestionDto result = wrongQuestionService.updateErrorReason(id, errorReason);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "错误原因已更新");
            response.put("data", result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新错误原因失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 更新复习笔记
     */
    @PutMapping("/{id}/review-notes")
    public ResponseEntity<Map<String, Object>> updateReviewNotes(
            @PathVariable Long id,
            @RequestParam String reviewNotes) {
        try {
            WrongQuestionDto result = wrongQuestionService.updateReviewNotes(id, reviewNotes);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "复习笔记已更新");
            response.put("data", result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新复习笔记失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 删除错题
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteWrongQuestion(@PathVariable Long id) {
        try {
            wrongQuestionService.deleteWrongQuestion(id);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "错题已删除");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "删除错题失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 批量删除错题
     */
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> deleteWrongQuestions(@RequestBody List<Long> ids) {
        try {
            wrongQuestionService.deleteWrongQuestions(ids);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "批量删除错题成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "批量删除错题失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 清空错题本
     */
    @DeleteMapping("/clear")
    public ResponseEntity<Map<String, Object>> clearWrongQuestions(@RequestParam Long userId) {
        try {
            wrongQuestionService.clearWrongQuestions(userId);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "错题本已清空");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "清空错题本失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取错题统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getWrongQuestionStats(@RequestParam Long userId) {
        try {
            Map<String, Object> stats = wrongQuestionService.getWrongQuestionStats(userId);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", stats);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取统计信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}
